package com.bsg.upm.controller;

import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bsg.upm.cache.DefinitionMetricCache;
import com.bsg.upm.constant.MonitorCommonMap;
import com.bsg.upm.dao.DefinitionMetricDao;
import com.bsg.upm.http.RespJson;
import com.bsg.upm.http.RespJsonFactory;
import com.bsg.upm.service.MonitorContainerService;
import com.bsg.upm.service.MonitorUnitService;

/**
 * 
 * @author yucs
 *
 */

@Controller
@RequestMapping("/v1.0/monitor/unit")
public class MonitorUnitController {

	@Resource
	private MonitorContainerService monitorContainerService;

	@Resource
	private MonitorUnitService monitorUnitService;

	@Resource
	private DefinitionMetricDao definitionMetricDao;

	@Resource
	private DefinitionMetricCache definitionMetricCache;

	@RequestMapping(value = "{unit_id}/{metric}", method = RequestMethod.GET)
	@ResponseBody
	public RespJson getMetric(@PathVariable("unit_id") String unitId, @PathVariable("metric") String metric,
			@RequestParam Map<String, Object> paramMap, HttpServletResponse response) {

		RespJson respJson = null;
		paramMap.put("unitId", unitId);
		paramMap.put("metric", metric);

		try {

			if (definitionMetricCache.isExist(MonitorCommonMap.CONTAINER_TYPE, metric)) {

				if (paramMap.containsKey("start_time") && paramMap.containsKey("end_time")) {
					respJson = monitorContainerService.historyHandle(paramMap);
				} else {
					respJson = monitorContainerService.noHistoryHandle(paramMap);
				}

				return respJson;
			}

			String unitType = monitorContainerService.getUnitType(unitId);
			paramMap.put("type", unitType);
			
			if (!definitionMetricCache.isExist(unitType, metric)) {
				response.setStatus(HttpStatus.SC_BAD_REQUEST);
				return RespJsonFactory.build(HttpStatus.SC_BAD_REQUEST, unitType + ":don't find the metric");
			}

			if (paramMap.containsKey("start_time") && paramMap.containsKey("end_time")) {
				respJson = monitorUnitService.historyHandle(paramMap);
			} else {
				respJson = monitorUnitService.noHistoryHandle(paramMap);
			}

			return respJson;

		} catch (Exception e) {
			response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			respJson = RespJsonFactory.build(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
		}

		return respJson;

	}

}
